package com.mackyhuang.annotated.enhancer.enhancer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: mackyHuang
 * @create: 2021/01/16
 */
public class EnhanceDriver {

    public static Map<String, Object> proxyObjectPool = new ConcurrentHashMap<>();

    public static Object prepare(Object target, Class adapter, Class annotation) throws IllegalAccessException, InstantiationException {
        //创建增强管理类
        Enhancement enhancement = new Enhancement();
        //通过Class创建目标类的实例
        EnhanceAdapter adapterObj = (EnhanceAdapter) adapter.newInstance();
        //调用管理类的Bind方法返回一个被增强后的实例
        Object result = enhancement.doProxy(target, adapterObj, annotation);
        String key = proxyPoolKeyRing(target.getClass(), adapter, annotation);
        bindProxyObjectToPool(result, key);
        return result;
    }

    public static String proxyPoolKeyRing(Class target, Class adapter, Class annotation){
        return new StringBuilder().append(target.hashCode()).append(adapter.hashCode()).append(annotation.hashCode()).toString();

    }

    private static void bindProxyObjectToPool(Object proxyObject, String key){
        if (proxyObject != null){
            proxyObjectPool.put(key, proxyObject);
        }
    }
}
